<?php
/**
 *                 Created In 2018/6/15 下午3:14.
 * ==============================================================
 *    Copyright © 2018 by wangHu. All rights reserved.
 *
 *                This is not a free software
 *    Author authorization, please do not open source or modify.
 * ==============================================================
 */

namespace api\common\controllers;

use yii\filters\auth\QueryParamAuth;
use yii\rest\Controller;

class ApiController extends Controller
{
    //设置认证方式
    public function behaviors ()
    {
        $behaviors = parent::behaviors();

        $behaviors[ 'authenticator' ] = [
            'class' => QueryParamAuth::className() ,
        ];

        return $behaviors;
    }

    //禁止访问Index方法
    protected function verbs ()
    {
        return [
            'index' => [] ,
        ];
    }

    //注销系统自带的实现方法
    public function actions ()
    {
        $actions = parent::actions();
        unset( $actions[ 'index' ] , $actions[ 'update' ] , $actions[ 'create' ] , $actions[ 'delete' ] , $actions[ 'view' ] );

        return $actions;
    }

    //设置响应格式
    public function beforeAction ( $action )
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        return parent::beforeAction( $action );
    }

    /**
     * @param      $return_code
     * @param      $return_msg
     * @param null $return_body
     *
     * @return array 返回消息处理
     */
    static function isMessage ( $return_code , $return_msg , $return_body = NULL )
    {
        $message = [
            'status' => $return_code ,
            'msg'    => is_array( $return_msg ) ? array_values( $return_msg )[ 0 ] : $return_msg ,
            'body'   => $return_body ,
        ];

        return $message;
    }

    function str_rand($length = 32, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
            if(!is_int($length) || $length < 0) {
                     return false;
             }
            $string = '';
            for($i = $length; $i > 0; $i--) {
                $string .= $char[mt_rand(0, strlen($char) - 1)];
             }
             return $string;
  }
}